<style>
    .mask {
        display: flex;
        position: fixed;
        height: 100%;
        width: 100%;
        background: rgba(0, 0, 0, 0.6);
        top: 0;
        left: 0;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }

    .content-top {
        color: #000;
        font-size: 20px;
        font-weight: 500;
        height: 40px;
        line-height: 40px;
        text-align: center;
        border-bottom: 1px solid #C9C5C5;
    }

    .cropper-mask .uploaded-content {
        width: 65%;
        padding-bottom: 10px;
        border-radius: 5px;
        background: #fff;
    }

    .cropper-mask .uploaded-content .choose-image {
        margin: 7px 0 0 7px;
    }

    .count-box {
        font-size: 14px;
        font-weight: 600;
        float: right;
        margin: 1%;
        height: 34px;
        line-height: 34px;
    }

    #cropper-box .uploaded-content-btn {
        padding: 1%;
    }

    #cropper-box .image-box {
        height: 350px;
        width: 60%;
        float: left;
        margin-left: 1%;
    }

    #image {
        /* 这个规则很重要，请不要忽略这个 */
        max-width: 100%;
    }

    #cropper-box .confirm-crop {
        width: 60%;
        float: left;
        margin: 7px 1% 0 1%;
    }

    #cropper-box .preview-cropper-box {
        width: 38%;
        height: 350px;
        float: right;
    }

    #preview {
        width: 98%;
        height: 100%;
        overflow: hidden;
    }

    #cropper-box .crop-info {
        width: 37%;
        height: 33px;
        float: left;
        margin: 7px 1% 0 0;
    }

    #cropper-box .crop-info div {
        float: left;
        width: 50%;
        padding: 0 2%;
    }

    #cropper-box .crop-info div span {
        font-size: 14px;
        font-weight: 600;
        line-height: 33px;
    }

    #cropper-box .crop-info .info-left {
        display: inline-block;
        width: 35%;
        height: 33px;
        text-align: center;
        border: 1px solid #C9C5C5;
        border-top-left-radius: 5px;
        border-bottom-left-radius: 5px;
        background: #E9ECEF;
    }

    #cropper-box .crop-info .width-data, #cropper-box .crop-info .height-data {
        display: inline-block;
        width: 40%;
        height: 33px;
        text-align: center;
        border-top: 1px solid #C9C5C5;
        border-bottom: 1px solid #C9C5C5;
    }

    #cropper-box .crop-info .info-right {
        display: inline-block;
        width: 25%;
        height: 33px;
        text-align: center;
        border: 1px solid #C9C5C5;
        border-top-right-radius: 5px;
        border-bottom-right-radius: 5px;
        background: #E9ECEF;
    }

    .cropper-mask .uploaded-content .uploaded-box {
        width: 98%;
        height: 140px;
        margin: 1%;
        border: 1px solid #C9C5C5;
        border-radius: 5px;
        overflow-x: auto;
        overflow-y: hidden;
        /* 强制不换行 */
        white-space: nowrap;
    }

    .cropper-mask .uploaded-content .uploaded-img-box {
        position: relative;
        display: inline-block;
    }

    .cropper-mask .uploaded-content .uploaded-box img {
        margin: 5px 0 5px 5px;
        width: 128px;
        height: 128px;
        object-fit: cover;
        border-radius: 5px;
    }

    .cropper-mask .uploaded-content .uploaded-img-box .uploaded-img-del {
        position: absolute;
        top: 18px;
        right: 13px;
        width: 26px;
        height: 26px;
        text-align: center;
        line-height: 26px;
        transform: translate(50%, -50%);
        color: #fff;
        background: rgba(0, 0, 0, 0.5);
    }

    .cropper-mask .uploaded-content .uploaded-img-box .uploaded-img-preview {
        position: absolute;
        font-size: 26px;
        top: 69px;
        right: 64px;
        width: 40px;
        height: 40px;
        text-align: center;
        line-height: 40px;
        transform: translate(50%, -50%);
        color: #fff;
        border-radius: 10px;
        background: rgba(0, 0, 0, 0.5);
    }

    .cropper-mask .uploaded-content .footer-box {
        text-align: center;
    }
</style>

<script src="__STATIC__/jquery/jquery-3.1.1.min.js"></script>
<link rel="stylesheet" href="__PLUG__/cropper/css/cropper.css">
<script src="__PLUG__/cropper/js/cropper.min.js" type="text/javascript"></script>

<div class="mask cropper-mask" style="display: none">
    <div class="uploaded-content">
        <div class="content-top">图片上传</div>

        <input type="file" id="original_file" accept="image/*" multiple="multiple" style="display: none">
        <input type="file" id="cropper_file" accept="image/*" style="display: none">
<!--        <button class="btn btn-w-m btn-primary choose-image" onclick="originalChooseImg('original_file')">原图</button>-->
        <button class="btn btn-w-m btn-primary choose-image" onclick="cropChooseImg('cropper_file', 'cropper-box')">裁剪</button>

        <div class="count-box">本次最多上传图片<span class="can-upload-count"></span>张</div>
        <div style="clear: both"></div>

        <div id="cropper-box" style="display: none">
            <div class="uploaded-content-btn">
                <button class="btn btn-w-m btn-primary" onclick="updateCropperBoxSize(this)" data-width_ratio="0" data-height_ratio="0">自由裁剪</button>
                <button class="btn btn-w-m btn-primary" onclick="updateCropperBoxSize(this)" data-width_ratio="5" data-height_ratio="4">微信小程序分享图</button>
                <button class="btn btn-w-m btn-primary" onclick="updateCropperBoxSize(this)" data-width_ratio="1" data-height_ratio="1">1/1</button>
                <button class="btn btn-w-m btn-primary" onclick="updateCropperBoxSize(this)" data-width_ratio="4" data-height_ratio="3">4/3</button>
                <button class="btn btn-w-m btn-primary" onclick="updateCropperBoxSize(this)" data-width_ratio="3" data-height_ratio="4">3/4</button>
                <button class="btn btn-w-m btn-primary" onclick="updateCropperBoxSize(this)" data-width_ratio="16" data-height_ratio="9">16/9</button>
                <button class="btn btn-w-m btn-primary" onclick="updateCropperBoxSize(this)" data-width_ratio="9" data-height_ratio="16">9/16</button>
                <button class="btn btn-w-m btn-primary" onclick="updateCropperBoxSize(this)" data-width_ratio="3" data-height_ratio="2">3/2</button>
                <button class="btn btn-w-m btn-primary" onclick="updateCropperBoxSize(this)" data-width_ratio="2" data-height_ratio="3">2/3</button>
            </div>

            <div class="image-box">
                <img id="image" src="">
            </div>
            <div class="preview-cropper-box">
                <div id="preview"></div>
            </div>

            <button class="btn btn-w-m btn-primary confirm-crop" onclick="crop()">确认裁剪</button>
            <div class="crop-info">
                <div class="width">
                    <span class="info-left">宽 度</span><span class="width-data">0</span><span class="info-right">px</span>
                </div>
                <div class="height">
                    <span class="info-left">高 度</span><span class="height-data">0</span><span class="info-right">px</span>
                </div>
            </div>
        </div>

        <div style="clear: both;"></div>

        <div class="uploaded-box" id="[crop_preview_box]">

        </div>

        <div class="footer-box">
            <button class="btn btn-w-m btn-danger" onclick="closeCrop()">取消上传</button>
            <button class="btn btn-w-m btn-primary" onclick="confirmComplete()">确认上传</button>
        </div>
    </div>
</div>

<script>
    var image = document.getElementById('image');
    initCropImage(image, $('#preview'));

    var [cropper_uploaded_img_ids] = [];
    var [cropper_uploaded_img_paths] = [];

    /********************   裁剪上传    ********************/
      // 裁剪图片实例对象
    var cropper;
    // form表单上传图片预览框ID，用户裁剪图片，确认上传时，将上传的图片添加到form表单的预览框中
    var form_uploaded_box_id;
    // form表单已上传图片数量
    var uploaded_count = 0;
    // 最多上传图片数量
    var max_upload_count = 0;
    // 本次可上次图片数量
    var can_upload_count = 0;

    // 打开裁剪框
    function openCrop(form_uploaded_box = '', max_count = 9) {
        form_uploaded_box_id = form_uploaded_box;

        // 表单已上传图片数量
        uploaded_count = $('#' + form_uploaded_box_id).find('img').length;
        // 最多上传图片数量
        max_upload_count = max_count;
        // 本次可上次图片数量
        can_upload_count = max_count == 1 ? 1 : max_upload_count - uploaded_count;
        $('.can-upload-count').html(can_upload_count);

        $('.cropper-mask').show();

        if (can_upload_count == 1) {
            $('#original_file').removeAttr('multiple');
        } else {
            $('#original_file').attr('multiple', 'multiple');
        }
    }

    // 关闭裁剪框
    function closeCrop() {
        $('.cropper-mask').hide();
        $('#cropper-box').hide();
        $('.uploaded-box').html('');
        [cropper_uploaded_img_ids] = [];
        [cropper_uploaded_img_paths] = [];
        cropper.destroy();

        $(".swiper-wrapper").html('');// swiper轮播图赋空

    }

    /**
     * 裁剪图片上传
     * @param {Element} imageObj 图片对象
     * @param {Element} previewElement 预览盒子
     * @param {Number} aspectRatio 定义裁剪框的固定宽高比。默认是自由比例（NaN）
     * @param {Number} minCropBoxWidth 裁剪框的最小宽度
     * @param {Number} minCropBoxHeight 裁剪框的最小高度
     * */
    function initCropImage(imageObj, previewElement = '', aspectRatio = NaN, minCropBoxWidth = 0, minCropBoxHeight = 0) {
        cropper = new Cropper(imageObj, {
            dragMode: 'crop', // 定义裁剪器的拖动模式；（默认）crop：创建一个新的裁剪框，move：图片容器可移动，none：什么也不做
            aspectRatio: aspectRatio,// 定义裁剪框的固定宽高比。默认是自由比例（NaN）
            preview: previewElement,// 预览
            minCropBoxWidth: minCropBoxWidth,// 裁剪框的最小宽度
            minCropBoxHeight: minCropBoxHeight// 裁剪框的最小高度
        });

        // 当图片容器或裁剪框更改时触发
        imageObj.addEventListener('crop', (event) => {
            var width = parseInt(event.detail.width),
              height = parseInt(event.detail.height);

            $('.width-data').html(width);
            $('.height-data').html(height);
        })
    }

    /**
     * 点击比例按钮修改裁剪框的位置和尺寸
     * */
    function updateCropperBoxSize(that) {
        var width_ratio = $(that).data('width_ratio');
        var height_ratio = $(that).data('height_ratio');

        var ratio = width_ratio > 0 && height_ratio > 0 ? width_ratio / height_ratio : NaN;

        // 将图片和裁剪框重置为初始状态比例
        cropper.reset();

        // 保持裁剪框的宽高比
        cropper.setAspectRatio(ratio);
    }

    /**
     * 选择裁剪的图片
     * @param {string} input_file 文件上传input的id
     * @param {string} cropper_box_id 裁剪图片上传盒子id
     * */
    var uploadedImageURL;

    function cropChooseImg(input_file, cropper_box_id) {
        if ([cropper_uploaded_img_ids].length < can_upload_count || max_upload_count == 1) {
            var file_obj = document.querySelector('#' + input_file);
            file_obj.click();
            file_obj.addEventListener('change', function () {
                var pics = document.querySelector('#' + input_file).files;
                if (pics.length > 0) {
                    // 确定上传图片
                    var file = $(this)[0].files[0];

                    if (/^image\/\w+$/.test(file.type)) {
                        $('#' + cropper_box_id).show();

                        if (uploadedImageURL) URL.revokeObjectURL(uploadedImageURL);
                        uploadedImageURL = URL.createObjectURL(file);

                        cropper.replace(uploadedImageURL);
                    } else {
                        layer.msg('请选择图片文件')
                    }
                }
                clearFile(input_file);
            })
        } else {
            layer.msg('本次图片最多上传' + can_upload_count + '张图片');
        }
    }

    /**
     * 确认裁剪上传图片
     * */
    function confirmCrop(callback) {
        if ([cropper_uploaded_img_ids].length < can_upload_count || max_upload_count == 1) {
            if (cropper) {
                layer.msg('裁剪中...', {
                    icon: 16
                    , shade: 0.01
                });
                cropper.getCroppedCanvas().toBlob((blob) => {
                    const formData = new FormData();

                    // 如果需要的话，将图片的文件名作为第三个参数传递
                    formData.append('download', blob);

                    $.ajax('/upload/UploadFile/uploadPicture', {
                        method: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success(res) {
                            callback(res);
                        },
                        error(err) {
                            callback(err);
                        },
                    });
                });
            } else {
                layer.msg('裁剪对象缺失')
            }
        } else {
            layer.msg('本次图片最多上传' + can_upload_count + '张图片');
        }
    }

    /**
     * 确认裁剪
     * */
    function crop() {
        confirmCrop(res => {
            if (res.status == 1) {
                var id = res.data.id,
                  path = res.data.path;

                // 单图上传数据处理
                if ([cropper_uploaded_img_ids] && max_upload_count == 1) {
                    [cropper_uploaded_img_ids] = [id];
                    [cropper_uploaded_img_paths] = [path];
                    renderPreviewImg(id, path, '[crop_preview_box]', true, 1)
                }

                // 多图上传数据处理
                if ([cropper_uploaded_img_ids].length < can_upload_count && max_upload_count > 1) {
                    [cropper_uploaded_img_ids].push(id);
                    [cropper_uploaded_img_paths].push(path);
                    renderPreviewImg(id, path, '[crop_preview_box]', true, can_upload_count)
                }

                layer.closeAll();
            } else {
                layer.msg('失败')
            }

        })
    }

    // 确认上传
    function confirmComplete() {
        new Promise(resolve => {
            $.each([cropper_uploaded_img_paths], (key, val) => {
                renderPreviewImg([cropper_uploaded_img_ids][key], val, form_uploaded_box_id, false, max_upload_count)
            })
            resolve(true);
        }).then(() => {
            // form表单已上传图片id
            var upload_img_id = $('#' + form_uploaded_box_id).val();
            $.each($('#' + form_uploaded_box_id).find('img'), (k, v) => {
                var img_id = $(v).data('id') || $(v).attr('src');

                if (max_upload_count == 1) {
                    // 单图上传
                    upload_img_id = img_id
                } else {
                    // 多图上传
                    if (upload_img_id == '') {
                        upload_img_id = img_id;
                    } else {
                        upload_img_id += ',' + img_id;
                    }
                }
            })
            $('#' + form_uploaded_box_id).parent().find(".hidden_value").val(upload_img_id);

            closeCrop();
        })
    }

    /********************   原图上传    ********************/
    /**
     * @param    file_id        file上传按钮id
     * */
    function originalChooseImg(file_id) {
        if ([cropper_uploaded_img_ids].length < can_upload_count || max_upload_count == 1) {
            var file_obj = document.querySelector('#' + file_id);
            file_obj.click();
            file_obj.addEventListener('change', function () {
                var pics = document.querySelector('#' + file_id).files;
                if (pics.length > 0) {
                    // 确定上传图片
                    for (var i = 0; i < pics.length; i++) {
                        if (max_upload_count - uploaded_count - i > 0 || max_upload_count == 1) {
                            var formData = new FormData();
                            var url = "/upload/UploadFile/uploadPicture";
                            formData.append('download', pics[i]);
                            $.ajax({
                                url: url,
                                type: "post",
                                data: formData,
                                cache: false,
                                contentType: false,
                                processData: false,
                                success: function (data) {
                                    if (data.status == 1) {
                                        //上传成功
                                        var id = data.data.id;
                                        var path = data.data.path;

                                        // 单图上传数据处理
                                        if ([cropper_uploaded_img_ids] && max_upload_count == 1) {
                                            [cropper_uploaded_img_ids] = [id];
                                            [cropper_uploaded_img_paths] = [path];
                                            renderPreviewImg(id, path, '[crop_preview_box]', true, 1)
                                        }

                                        // 多图上传数据处理
                                        if ([cropper_uploaded_img_ids].length < can_upload_count && max_upload_count > 1) {
                                            [cropper_uploaded_img_ids].push(id);
                                            [cropper_uploaded_img_paths].push(path);
                                            renderPreviewImg(id, path, '[crop_preview_box]', true, can_upload_count)
                                        }
                                    } else {
                                        layer.msg(data.info);
                                    }
                                }
                            })
                        } else {
                            layer.msg('本次图片最多上传' + can_upload_count + '张图片');
                        }
                    }
                }
                clearFile(file_id)
            })
        } else {
            layer.msg('本次图片最多上传' + can_upload_count + '张图片');
        }
    }
</script>